#include "MyLog.h"

#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>

#define LOG_BUF_SIZE 1024

static MyLog *mLog = nullptr;
#define TIME_OFFSET 12
MyLog::MyLog()
{
    time(&RunTime);
    struct tm *t = gmtime(&RunTime);
    t->tm_year += 1900;
    t->tm_mon += 1;
    t->tm_hour += 8;
    FileName[TIME_OFFSET + 0] += t->tm_year / 10 % 10; 
    FileName[TIME_OFFSET + 1] += t->tm_year % 10; 
    FileName[TIME_OFFSET + 3] += t->tm_mon / 10; 
    FileName[TIME_OFFSET + 4] += t->tm_mon % 10; 
    FileName[TIME_OFFSET + 6] += t->tm_mday / 10; 
    FileName[TIME_OFFSET + 7] += t->tm_mday % 10; 
    FileName[TIME_OFFSET + 9] += t->tm_hour / 10; 
    FileName[TIME_OFFSET + 10] += t->tm_hour % 10; 
    FileName[TIME_OFFSET + 12] += t->tm_min / 10; 
    FileName[TIME_OFFSET + 13] += t->tm_min % 10; 

    FileName[6] = 'R';
    FileName[7] = 'u';
    FileName[8] = 'n';
    LogFd = open(FileName, O_WRONLY | O_APPEND | O_CREAT, 0777);
    if (LogFd == -1)
        return ;
    FileName[6] = 'E';
    FileName[7] = 'r';
    FileName[8] = 'r';
    ErrorLogFd = open(FileName, O_WRONLY | O_APPEND | O_CREAT, 0777);
    if (LogFd == -1)
        return ;
}

MyLog::~MyLog()
{
    close(LogFd);
}

int MyLog::printLog(const char *fmt, ...)
{
    char buf[LOG_BUF_SIZE];

    va_list ap;
    va_start(ap, fmt);
    int ret = vsnprintf_s(buf, sizeof(buf), LOG_BUF_SIZE - 1, fmt, ap);
    if (ret == -1) {
        va_end(ap);
        return -1;
    }
    va_end(ap);
}

MyLog *MyLog::getInstance()
{
    if (mLog == nullptr){
        mLog = new MyLog();
        if (mLog != nullptr && mLog->LogFd == -1){
            delete mLog;
        }
    }
    return mLog;
}


int MyLog::writeLog(const char *str)
{
    int i = 0;
    time_t timep;
    char timeBuf[20]={0};
    time (&timep);
    sprintf(timeBuf, "[%u]", (unsigned int)(timep-RunTime));
    while (timeBuf[i]){
        i++;
    }
    write(LogFd, timeBuf, i);
    i = 0;
    while (str[i]){
        i++;
    }
    write(LogFd, str, i);
    if (str[i - 2] != '\r'){
        write(LogFd, "\r\n", 2);
    }
    return i;
}

int MyLog::writeErrorLog(const char *str)
{
    int i = 0;
    char timeBuf[20]={0};
    time_t timep;
    time (&timep);
    sprintf(timeBuf, "[%u]", (unsigned int)(timep-RunTime));
    while (timeBuf[i]){
        i++;
    }
    write(ErrorLogFd, timeBuf, i);
    i = 0;
    while (str[i]){
        i++;
    }
    write(ErrorLogFd, str, i);
    if (str[i - 2] != '\r'){
        write(LogFd, "\r\n", 2);
    }
    return i;
}

MyLog &MyLog::operator<<(const char *str)
{
    writeLog(str);
}
